import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Modal, Form, message } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import BrandManagementStyle from './BrandManagement.module.css'
import { connect } from 'react-redux';
import Store from './../../store/index';
import * as Action from '../../store/actions/goods/action'
// 1.映射State到props:
function mapStateToProps(state) {
    return {
        data: state.GoodsAttr.GoodsLabel
    }
}
// 2. 映射方法到props:
function mapDispatchToProps(dispatch) {
    return {
        LabelEdit: (id, obj) => { dispatch(Action.LabelEditBtn(id, obj)) },
        LabelDel: (id) => { dispatch(Action.LabelDelBtn(id)) },
        labelAdd: (obj) => { dispatch(Action.LabelAddBtn(obj)) }
    }
}
const GoodsLabel = (props) => {
    const { LabelEdit, labelAdd, LabelDel } = props
    const { confirm } = Modal;
    // 打开关闭模态框
    const [open, setOpen] = useState(false);
    const [open2, setOpen2] = useState(false);
    // 添加编辑标题titleMap
    const [titleMap, setTitleMap] = useState()
    // 添加
    const [addForm] = Form.useForm()
    // 修改
    const [editForm] = Form.useForm()
    const [columns, setColumns] = useState([
        {
            title: '标签名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '商品数',
            dataIndex: 'GoodsNum',
            key: 'GoodsNum',
        },
        {
            title: '创建时间',
            dataIndex: 'date1',
            key: 'date1',
        },
        {
            title: '操作',
            dataIndex: '',
            render: (text) => (
                <div>
                    <Button type="link" onClick={() => edit1(text)}>编辑</Button>
                    <Button type="link" onClick={() => del(text)}>删除</Button>
                </div>
            )
        },

    ]);
    const [data, setData] = useState(Store.getState().GoodsAttr.GoodsLabel);
    // 查询
    const [LName, setLNme] = useState()
    // 输入框值
    const LNmeChange = (e) => {
        setLNme(e.target.value)

    }
    // 查询函数
    const queryFn = () => {
        let arr = [];
        clearTimeout(window.timer)//防抖查询
        window.timer = setTimeout(() => {
            let list = []
            props.data.forEach(el => {
                const condition = (LName !== '' && el.name.includes(LName))
                if (condition) {
                    list.push(el)
                }
                console.log("list", list);
            })
            setData(list)
        }, 500)

    }
    // 删除函数
    const del = (obj) => {

        confirm({
            title: '你确定删除当前行吗',
            icon: <ExclamationCircleFilled />,
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                LabelDel(obj.id)
                setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsLabel)))
                message.success('删除成功')

            },
            onCancel() {
                console.log('Cancel');
                message.error('删除失败')

            },
        });
    }
    // 新增函数
    const BrandAdd = () => {
        setOpen(true);
        addForm.setFieldsValue({
            "id": data.length + 1,
            "key": data.length + 1
        })
        setTitleMap('新增标签')
    }
    // 添加模态框确认按钮
    const handleOk = (values) => {
        labelAdd(values)
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsLabel)))
        setOpen(false);
        addForm.resetFields()
        message.success('操作成功')
    };
    // 添加模态框取消按钮
    const handleCancel = () => {
        setOpen(false);
        message.error('操作失败')
    };
    // 编辑函数
    const edit1 = (obj) => {
        setTitleMap('编辑标签')
        let showData = {};
        data.forEach(el => {
            if (el.id === obj.id) {
                showData = JSON.parse(JSON.stringify(el))
            }
        });
        // ...表示结构化
        editForm.setFieldsValue({ ...showData })
        console.log("show+++", showData);
        setOpen2(true)
    }


    // 编辑模态框确认按钮
    const handleOk2 = (values) => {
        LabelEdit(values.id, { ...values })
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsLabel)))
        setOpen2(false);
        message.success('操作成功')
        editForm.resetFields()

    };
    // 编辑模态框取消按钮
    const handleCancel2 = () => {
        setOpen2(false);
        message.error('操作失败')
    };
    // 验证规则失败执行此函数
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    // 获取当前时间
    const getCurrentTime = () => {
        var date = new Date();
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let D = date.getDate() + ' ';
        let h = date.getHours() + ':';
        let m = date.getMinutes() + ':';
        let s = date.getSeconds();

        let currentTime = Y + M + D + h + m + s
        console.log(Y + M + D + h + m + s);
        console.log('c', currentTime);
        return currentTime
    }


    return (
        <>
            <div className={BrandManagementStyle.title}>
                <div >
                    <Button type="primary" className={BrandManagementStyle.titleLeft} onClick={() => BrandAdd()}>新建标签</Button>
                </div>


                <div className={BrandManagementStyle.titleR}>
                    <Input placeholder="请输入标签名称" onChange={LNmeChange} style={{ width: '200px' }} value={LName} />
                    <Button type="link" onClick={() => queryFn()}>查询</Button>
                </div>
            </div>
            <Table columns={columns} dataSource={data} rowKey={record => record.id} />
            <Modal
                title={titleMap}
                open={open}
                closable={false}
                footer={null}
            >
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={handleOk}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={addForm}
                >
                    <Form.Item hidden name="id">
                        <Input />
                    </Form.Item>
                    <Form.Item name="date1" hidden initialValue={getCurrentTime()}>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="标签名称"
                        name="name"
                        placeholder='请输入'
                        rules={[
                            {
                                required: true,
                                message: '请输入正确的品牌名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item label="商品数" name="GoodsNum">
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}
                    >

                        <Form.Item >
                            <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                    确认
                                </Button>
                                <Button type="primary" onClick={handleCancel}>
                                    取消
                                </Button>
                            </div>
                        </Form.Item>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title={titleMap}
                open={open2}
                closable={false}
                footer={null}
                forceRender={true}
                destroyOnClose={false}
            >
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={handleOk2}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={editForm}
                >
                    <Form.Item hidden name="id">
                        <Input />
                    </Form.Item>
                    <Form.Item hidden name="date1">
                        <Input />
                    </Form.Item>
                    <Form.Item hidden name="GoodsNum">
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="标签名称"
                        name="name"
                        placeholder='请输入'
                        rules={[
                            {
                                required: true,
                                message: '请输入正确的品牌名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}
                    >
                        <Form.Item >
                            <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                    确认
                                </Button>
                                <Button type="primary" onClick={handleCancel2}>
                                    取消
                                </Button>
                            </div>
                        </Form.Item>
                    </Form.Item>
                </Form>
            </Modal>

        </>
    )
}
export default connect(mapStateToProps, mapDispatchToProps)(GoodsLabel)